<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    canvas {
      border: 1px solid #333;
    }
  </style>
</head>

<body>
  <canvas width="600" height="400"></canvas>
  <script>
    let canvas = document.querySelector("canvas")
    let ctx = canvas.getContext("2d")

    ctx.beginPath()
    ctx.fillStyle = "red"

    let x = 0, y = 0;
    let yTag = true;    //true 向下；false 向上
    let xTag = true;
    setInterval(() => {
      ctx.clearRect(x, y, 50, 50)
      // x++;
      // if (y >= 350) {
      //   y--
      // } else {
      //   y++
      // }
      if (x >= 550) {
        xTag = false;
      }
      if (x <= 0) {
        xTag = true
      }

      if (xTag) {
        x++
      } else {
        x--
      }

      if (y >= 350) {
        yTag = false;
      }
      if (y <= 0) {
        yTag = true
      }

      if (yTag) {
        y++
      } else {
        y--
      }

      console.log("x=", x, " y=", y)
      ctx.fillRect(x, y, 50, 50)
    }, 10);

  </script>

</body>

</html>